#-*- coding: utf-8 -*-
import hashlib
import json

from django.http import JsonResponse
from django.db import transaction

from account.auth import require_login
from account.models import *

def signin(request):
    username = request.POST['username']
    password = request.POST['password']
    label_list = request.POST['label_list']
    if len(username) == 0:
        return JsonResponse({'code': 1, 'msg': '请填写帐号'})

    try:
        label_list = json.loads(label_list)
        for i in label_list:
            if type(i) != int:
                return JsonResponse({'code': 2, 'msg': '参数格式错误'})
    except:
        return JsonResponse({'code': 2, 'msg': '参数格式错误'})

    
    account = Account.objects.filter(username=username).first()
    if account:
        return JsonResponse({'code': 3, 'msg': '帐号已存在'})

    password = hashlib.md5(password.encode('utf-8')).hexdigest()
    try:
        with transaction.atomic():
            account = Account.objects.create(username=username, password=password)
            for i in label_list:
                label = Label.objects.filter(id=i).first()
                if label:
                    UserLabel.objects.create(account=account, label=label)
    except:
        return JsonResponse({'code': 4, 'msg': '注册失败'}) 
    return JsonResponse({'code': 0})


def get_label_list(request):
    label_list = []
    for i in Label.objects.all().order_by('id'):
        label_list.append({
            'id': i.id,
            'name': i.name
        })

    data = {'label_list': label_list}
    return JsonResponse({'code': 0, 'data': data})


def login(request):
    username = request.POST['username']
    password = request.POST['password']
    password = hashlib.md5(password.encode('utf-8')).hexdigest()
    account = Account.objects.filter(username=username, password=password).first()
    if not account:
        return JsonResponse({'code': 1, 'msg': '帐号不存在或密码错误'})

    request.session['account_id'] = account.id
    return JsonResponse({'code': 0})


@require_login
def get_userinfo(request):
    account = request.account
    data = {
        'id': account.id,
        'username': account.username,
        'create_time': str(account.create_time)
    }
    return JsonResponse({'code': 0, 'data': data})


@require_login
def logout(request):
    del request.session['account_id']
    return JsonResponse({'code': 0})

@require_login
def get_image_list(request):
    query_string = request.POST['query_string']
    page_no = int(request.POST.get('page_no', '1'))
    account = request.account
    label_list = []
    for i in Label.objects.all():
        if i.name in query_string:
            label_list.append(i)
        elif UserLabel.objects.filter(account=account, label=i).first():
            label_list.append(i)
    page_size = 20
    start_index = (page_no - 1) * page_size

    _filter = Image.objects.filter(label__in=label_list)
    total_image_count = _filter.count()
    total_page_count = (total_image_count // page_size) + (0 if total_image_count % page_size == 0 else 1)
    image_list = []
    for image in _filter.order_by('-id')[start_index:start_index+page_size]:
        image_list.append({
            'key': image.key,
            'id': image.id,
            'url': image.url,
            'create_time': str(image.create_time)
        })

    data = {
        'page_size': page_size,
        'page_no': page_no,
        'total_image_count': total_image_count,
        'total_page_count': total_page_count,
        'image_list': image_list
    }
    return JsonResponse({'code': 0, 'data': data})


@require_login
def get_my_label_list(request):
    label_list = []
    for i in Label.objects.all().order_by('id'):
        is_selected = False
        if UserLabel.objects.filter(account=request.account, label=i).first():
            is_selected = True
        label_list.append({
            'id': i.id,
            'name': i.name,
            'is_selected': is_selected
        })

    data = {'label_list': label_list}
    return JsonResponse({'code': 0, 'data': data})


@require_login
def set_my_label_list(request):
    label_list = request.POST['label_list']
    try:
        label_list = json.loads(label_list)
        for i in label_list:
            if type(i) != int:
                return JsonResponse({'code': 2, 'msg': '参数格式错误'})
    except:
        return JsonResponse({'code': 2, 'msg': '参数格式错误'})
    
    account = request.account
    try:
        with transaction.atomic():
            UserLabel.objects.filter(account=account).delete()
            for i in label_list:
                label = Label.objects.filter(id=i).first()
                if label:
                    UserLabel.objects.create(account=account, label=label) 
    except:
        return JsonResponse({'code': 1, 'msg': '修改失败'})
    return JsonResponse({'code': 0})
